package u.hnx.admin.system.service.impl;


import cn.hutool.core.util.ObjectUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import u.hnx.admin.exception.sys.LoggedException;
import u.hnx.admin.exception.sys.UserLimitException;
import u.hnx.admin.query.user.LoginQuery;
import u.hnx.admin.security.api.CaptchaFilter;
import u.hnx.admin.security.api.CaptchaVerify;
import u.hnx.admin.security.api.LoginVerify;
import u.hnx.admin.security.api.SecurityVerifyAPI;
import u.hnx.admin.security.core.SecurityProperties;
import u.hnx.admin.support.redis.config.RedisCore;
import u.hnx.admin.utils.RequestParamsWapperUtil;

import java.io.IOException;
import java.util.Collection;

@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(SecurityProperties.class)
public class CaptchaFilterCustomizer implements CaptchaFilter, SecurityVerifyAPI {
    private final SecurityProperties securityProperties;
    private final RedisCore redisCore;
    private final LoginVerify loginVerify;
    private final CaptchaVerify captchaVerify;
    @Override
    public Authentication check(HttpServletRequest request) throws IOException {
        LoginQuery loginQuery = RequestParamsWapperUtil.getRequestAttributes(request);
        if (request.getServletPath().equalsIgnoreCase(securityProperties.getProcessesUrl())) {
            Object object = redisCore.getCache(LOGIN_TOKEN_KEY + loginQuery.getUsername());
            if(ObjectUtil.isNotNull(object)){
                throw new LoggedException(LOGGED);
            }
            String retryKey = loginVerify.getRetryKey(request);
            if(!loginVerify.isRetry(loginVerify.getRetryCount(retryKey))){
                throw new UserLimitException(RETRY_ERROR_COUNT);
            }
            Collection<String> keys =  redisCore.keys(LOGIN_TOKEN_KEY + "*");
            if(keys.size()>= securityProperties.getMaxNum()){
                throw new UserLimitException(USER_MAX_ERROR);
            }
            //注：如果需要有验证码功能，需要实现CaptchaVerify接口，默认没有作验证码处理
            captchaVerify.verifyCode(request,securityProperties);
        }
        return null;
    }
}
